(async () => {
  const utilsUrl = chrome.runtime.getURL('utils.js');
  console.log('utilsUrl:', utilsUrl);
  let utils = await import(utilsUrl);
  const storeUtilsUrl = chrome.runtime.getURL('utils_fastmoss_store.js');
  let storeUtils = await import(storeUtilsUrl);
  console.log('storeUtilsUrl:', storeUtilsUrl);
  const productUtilsUrl = chrome.runtime.getURL('utils_fastmoss_product.js');
  let productUtils = await import(productUtilsUrl);
  console.log('productUtilsUrl:', productUtilsUrl);

  // Make utils functions available globally for this script
  window.toPureNumber = utils.toPureNumber;
  window.extractTextFromNode = utils.extractTextFromNode; 
  window.extractNumberFromNode = utils.extractNumberFromNode;
  window.getNodeByXPath = utils.getNodeByXPath;
  window.getNodesByXPath = utils.getNodesByXPath;
  window.getAllTextContent = utils.getAllTextContent;
  window.extractKeyValuePairs = utils.extractKeyValuePairs;
  window.extractTableData = utils.extractTableData;
  window.getXPathAttributeValue = utils.getXPathAttributeValue;

  // Make store utils functions available globally
  window.getFastMossStoreId = storeUtils.getFastMossStoreId;
  window.extractFastmossStoreBasicInfo = storeUtils.extractFastmossStoreBasicInfo;
  window.extractFastmossStoreOverall = storeUtils.extractFastmossStoreOverall;
  window.extractFastmossStoreTrend28 = storeUtils.extractFastmossStoreTrend28;
  window.extractFastmossStoreDealAnalysis = storeUtils.extractFastmossStoreDealAnalysis;
  window.extractFastmossStoreGoodsAnalysis = storeUtils.extractFastmossStoreGoodsAnalysis;
  window.extractFastmossStoreGoodsList = storeUtils.extractFastmossStoreGoodsList;
  window.extractFastmossStoreInfluencerList = storeUtils.extractFastmossStoreInfluencerList;
  window.extractFastmossStoreSelfAccountOverall = storeUtils.extractFastmossStoreSelfAccountOverall;
  window.extractFastmossStoreLiveStreamOverall = storeUtils.extractFastmossStoreLiveStreamOverall;
  window.extractFastmossStoreLiveStreamList = storeUtils.extractFastmossStoreLiveStreamList;
  window.extractFastmossStoreVideoOverall = storeUtils.extractFastmossStoreVideoOverall;
  window.extractFastmossStoreVideoList = storeUtils.extractFastmossStoreVideoList;
  window.extractFastmossStoreDescription = storeUtils.extractFastmossStoreDescription;

  // // Make product utils functions available globally
  window.getFastMossProductId = productUtils.getFastMossProductId;
  window.extractFastmossProductDescription = productUtils.extractFastmossProductDescription;
  window.extractFastmossProductOverall = productUtils.extractFastmossProductOverall;
  window.extractFastmossProductBasicInfo = productUtils.extractFastmossProductBasicInfo;
  window.extractFastmossProductDataOverview = productUtils.extractFastmossProductDataOverview;
  window.extractFastmossProductDealAnalysis = productUtils.extractFastmossProductDealAnalysis;
  window.extractFastmossProductVideoList = productUtils.extractFastmossProductVideoList;
  window.extractFastmossProductLiveStreamList = productUtils.extractFastmossProductLiveStreamList;
  window.extractFastmossProductInfluencerList = productUtils.extractFastmossProductInfluencerList;
  window.extractFastmossProductReviewSummaryList = productUtils.extractFastmossProductReviewSummaryList;

  initContentScript();
})();

function initContentScript() {
  // 测试utils.js函数调用
  console.log('Testing utils.js functions...');
  
  // 测试getFastMossStoreId
  // const storeId = getFastMossStoreId();
  // console.log('getFastMossStoreId:', storeId);
  
  // 测试toPureNumber
  const testNumber1 = toPureNumber('100万');
  const testNumber2 = toPureNumber('1.5亿');
  console.log('toPureNumber:', { 
    '100万': testNumber1, 
    '1.5亿': testNumber2 
  });
  
  // 测试getNodeByXPath
  const bodyNode = getNodeByXPath('//body');
  console.log('getNodeByXPath:', bodyNode ? 'Success' : 'Failed');
  
  // 测试extractKeyValuePairs
  // const testPairs = extractKeyValuePairs(
  //   '//body', 
  //   './div[1]', 
  //   './div[2]'
  // );
  // console.log('extractKeyValuePairs:', testPairs);
  
  console.log('Utils.js function tests completed');

}

function extractFastmossProductSearchResultOnePage() {
  const keyword = getXPathAttributeValue('//*[@id="rc_select_1"]/attribute::value')
  // Extract table data from search results
  const headerXPath = '//*[@id="container"]/div[2]/div[2]/main/div/div/div[2]/div/div[2]/div/div/div/div/div/div/div/div/table/thead/tr/th'
  const rowXPath = '//*[@id="container"]/div[2]/div[2]/main/div/div/div[2]/div/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr[position()>1]'
  let result = extractTableData(headerXPath, rowXPath);

  // Post-process to extract price and category from "商品" field
  result.forEach(item => {
    item['搜索关键词'] = keyword;
    if (item['商品']) {
      const text = item['商品'].toString();
      const priceMatch = text.match(/售价 ： (\$\d+\.\d+(?: - \d+\.\d+)?)/);
      const categoryMatch = text.match(/售价 ： \$\d+\.\d+(?: - \d+\.\d+)?\s*(.+)$/);
      
      if (priceMatch) {
        const priceStr = priceMatch[1];
        if (priceStr.includes('-')) {
          // Handle price range
          const [minStr, maxStr] = priceStr.split('-').map(s => s.trim());
          item['售价L'] = parseFloat(minStr.replace(/[^\d.]/g, ''))
          item['售价H'] = parseFloat(maxStr.replace(/[^\d.]/g, ''))
        } else {
          // Handle single price
          item['售价L'] = item['售价H'] = parseFloat(priceStr.replace(/[^\d.]/g, ''));
        }
      }
      if (categoryMatch) {
        item['类目'] = categoryMatch[1].trim();
      }
      // Clean original 商品 field by removing price and category
      item['商品'] = text.split('售价')[0].trim();
    }
    if (item['所属店铺']) {
      const text = item['所属店铺'].toString();
      const texts = text.split('店铺销量：');
      item['所属店铺'] = texts[0].trim();
      if (texts.length > 1) {
        item['店铺销量'] = toPureNumber(texts[1].trim());
      } else {
        item['店铺销量'] = 0;
      }
    }
    return item;
  });
  
  return result;
}

// 注册消息监听器
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'scrollPage') {
    console.log('Received request to scroll page');
    const isAtBottom = (window.innerHeight + window.scrollY) >= document.body.scrollHeight - 10;  // 10px 缓冲，避免误判。因为有可能浮点运算误差导致永远滚不到底
    
    if (!isAtBottom) {
      window.scrollBy({
        top: window.innerHeight,
        behavior: 'smooth'
      });
      sendResponse({ status: 'Scrolling' });
    } else {
      sendResponse({ status: 'Scrolled to end' });
    }
  }
  else if (request.action === 'switchPage') {
    console.log('Received request to switch page');
    
    const nextPageButton = getNodeByXPath('//li[@title="下一页" and @aria-disabled="false"]/button');
    if (nextPageButton) {
      nextPageButton.click();
      console.log('Found next page button');
      sendResponse({ status: 'Switching page' });
    } else {
      console.log('Next page button not found');
      sendResponse({ status: 'Switched to end' });
    }
    
  }
  else if (request.action === 'extractFastmossProduct') {
    const productId = getFastMossProductId();
    if (!productId) {
      sendResponse({ error: 'Product ID not found' });
      return;
    }
    const productDescription = extractFastmossProductDescription();    
    const basicInfo = extractFastmossProductBasicInfo();
    const productOverall = extractFastmossProductOverall();
    const dataOverview = extractFastmossProductDataOverview();
    const dealAnalysis = extractFastmossProductDealAnalysis();
    const videoList = extractFastmossProductVideoList();
    const liveStreamList = extractFastmossProductLiveStreamList();
    const influencerList = extractFastmossProductInfluencerList();
    const reviewSummaryList = extractFastmossProductReviewSummaryList();
    const result = { productId, productDescription, basicInfo, productOverall, dataOverview, dealAnalysis, videoList, liveStreamList, influencerList, reviewSummaryList };
    console.log('extractFastmossProduct:', result);
    sendResponse({ result });
  }
  else if (request.action === 'extractFastmossStore') {
    const storeId = getFastMossStoreId();
    if (!storeId) {
      sendResponse({ error: 'Store ID not found' });
      return;
    }
    const storeDesciption = extractFastmossStoreDescription();
    const basicInfo = extractFastmossStoreBasicInfo();
    const overallData = extractFastmossStoreOverall();
    const trendData = extractFastmossStoreTrend28();
    const dealAnalysis = extractFastmossStoreDealAnalysis();
    const goodsAnalysis = extractFastmossStoreGoodsAnalysis();
    const goodsList = extractFastmossStoreGoodsList();
    const influencerList = extractFastmossStoreInfluencerList();
    const selfAccountOverall = extractFastmossStoreSelfAccountOverall();
    const liveStreamOverall = extractFastmossStoreLiveStreamOverall();
    const liveStreamList = extractFastmossStoreLiveStreamList();
    const videoOverall = extractFastmossStoreVideoOverall();
    const videoList = extractFastmossStoreVideoList();
    const result = { storeId, storeDesciption, basicInfo, overallData, trendData, dealAnalysis, goodsAnalysis, goodsList, influencerList, selfAccountOverall, liveStreamOverall, liveStreamList, videoOverall, videoList };
    console.log('extractFastmossStore:', result);
    sendResponse({ result });
  }
  else if (request.action === 'extractProductSearchResult') {
    try {
      result = extractFastmossProductSearchResultOnePage();
      
      console.log('extractProductSearchResult:', result);
      sendResponse({ result });
    } catch (error) {
      console.error('Error extracting product search results:', error);
      sendResponse({ error: error.message });
    }
  }
  else if (request.action === 'getAllSearchResultsLink') {
    try {
      const xpath = '//*[@id="container"]/div[2]/div[2]/main/div/div/div[2]/div/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr/td[1]/span/a';
      const nodes = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
      const links = [];
      
      for (let i = 0; i < nodes.snapshotLength; i++) {
        const node = nodes.snapshotItem(i);
        if (node && node.href) {
          links.push(node.href);
        }
      }
      
      console.log('Extracted search result links:', links);
      sendResponse(links.length > 0 ? links : []);
    } catch (error) {
      console.error('Error getting search result links:', error);
      sendResponse([]);
    }
  }
});
